package com.cct.digitalarchapi.service.impl;

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.documents.WatermarkLayout;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cct.digitalarchapi.common.Constant;
import com.cct.digitalarchapi.common.Response;
import com.cct.digitalarchapi.dao.*;
import com.cct.digitalarchapi.pojo.*;
import com.cct.digitalarchapi.pojo.dto.ArchLabelDto;
import com.cct.digitalarchapi.pojo.dto.ArchMainDto;
import com.cct.digitalarchapi.pojo.dto.ArchTypeAndNumDto;
import com.cct.digitalarchapi.pojo.dto.CateAndYearDto;
import com.cct.digitalarchapi.pojo.vo.ArchMainCountVo;
import com.cct.digitalarchapi.pojo.vo.ArchMainMonthVo;
import com.cct.digitalarchapi.pojo.vo.ArchMainTypeVo;
import com.cct.digitalarchapi.pojo.vo.ArchTypeAndNumVo;
import com.cct.digitalarchapi.service.DigitalArchMainService;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.spire.doc.fields.DocPicture;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @FileName DigitalArchMainServiceImpl
 * @Description 实现类
 * @Author Created by chenmingzhe
 * @Date 2023/11/19
 **/
@Slf4j
@Service
public class DigitalArchMainServiceImpl implements DigitalArchMainService {

    @Autowired
    private DigitalArchMainMapper digitalArchMainMapper;
    @Autowired
    private DigitalArchFilesMapper digitalArchFilesMapper;
    @Autowired
    private ArchCategoryMapper archCategoryMapper;
    @Autowired
    private Constant constant;
    @Autowired
    private ArchApplicationMapper archApplicationMapper;
    @Autowired
    private ArchLabelMainMapper archLabelMainMapper;
    @Autowired
    private MessageMapper messageMapper;

    @Override
    public Response addArchMain(DigitalArchMain digitalArchMain) {
        try {
            digitalArchMain.setBorrowCount(0);
            digitalArchMain.setVisitCount(0);
            digitalArchMainMapper.addArchMain(digitalArchMain);
            //消息记录
            Message message=new Message();
            message.setType(1);
            message.setMessState(0);
            message.setOperator(digitalArchMain.getStaffCode());
            if(StringUtils.isBlank(digitalArchMain.getStaffCode())){
                message.setMessContent("您有待审批的档案归档，档案名称为："+ digitalArchMain.getArchTitle());
            }else{
                message.setMessContent("您有待审批的档案归档，档案名称为："+ digitalArchMain.getArchTitle()+" ，档案归档提交人："+digitalArchMain.getStaffCode());
            }
            messageMapper.addMessge(message);
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新增档案失败：{}", e.getMessage());
            return Response.error("新增档案失败");
        }
    }

    @Override
    public Response updateCount(String type, int archMainId) {
        try {
            if ("1".equals(type)) {
                digitalArchMainMapper.updateVisitCount(archMainId);
            } else if ("2".equals(type)) {
                digitalArchMainMapper.updateDownCount(archMainId);
            } else {
                return Response.bad("type类型不合法");
            }
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新次数失败：{}", e.getMessage());
            return Response.error("更新次数失败");
        }
    }

    @Override
    public Response qryAllArchMain(int pageNum, int pageSize) {
        try {
            Page<DigitalArchMain> page = new Page<>(pageNum, pageSize);
            digitalArchMainMapper.qryAllArchMain(page);
            return Response.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询所有档案失败：{}", e.getMessage());
            return Response.error("查询所有档案失败");
        }
    }

    @Override
    public Response qryArchMainById(int archMainId) {
        try {
            DigitalArchMain digitalArchMain = digitalArchMainMapper.qryArchMainById(archMainId);
            return Response.success(digitalArchMain);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据Id查询档案失败：{}", e.getMessage());
            return Response.error("根据Id查询档案失败");
        }
    }


    @Override
    public Response qryAllArchMainByType(int pageNum, int pageSize, int accessState, String archState, String archCateCode, String archDeptCode, String username, String staffCode,String archTitle
    ,int archPeriod,int visitCount,int borrowCount,String submitYear,String archDeptHotName) {
        try {
            Page<DigitalArchMain> page = new Page<>(pageNum, pageSize);
            //送空查所有
            if("".equals(archState)){
                int state=-1;
                digitalArchMainMapper.qryAllArchMainByType(page, accessState, state, archCateCode, archDeptCode, username, staffCode,archTitle
                        ,archPeriod,visitCount,borrowCount,submitYear,archDeptHotName);
            }else {
                String[] res = archState.split(",");
                List<String> list = Arrays.asList(res);
                if (list.size() == 1) {
                    //单个时根据状态查
                    int state = Integer.parseInt(list.get(0));
                    digitalArchMainMapper.qryAllArchMainByType(page, accessState, state, archCateCode, archDeptCode, username, staffCode, archTitle
                            ,archPeriod,visitCount,borrowCount,submitYear,archDeptHotName);
                } else {
                    StringBuffer sb = new StringBuffer();
                    for (String s : list) {
                        sb.append("'").append(s).append("'").append(",");
                    }
                    String stateList="("+sb.toString().substring(0, sb.toString().length() - 1)+")";
                    digitalArchMainMapper.qryAllArchMainWithList(page, accessState, stateList, archCateCode, archDeptCode, username, staffCode, archTitle
                            ,archPeriod,visitCount,borrowCount,submitYear,archDeptHotName);
                }
            }
            if(page.getRecords().size()>0){
                for (DigitalArchMain record : page.getRecords()) {
                    List<ArchLabelDto> list=archLabelMainMapper.qryArchLabel(record.getArchMainId());
                    record.setArchLblId(0);
                    record.setHaveDetail("0");
                    if(list.size()!=0){
                        if(list.get(0).getArchLblId()!=0){
                            record.setArchLblId(list.get(0).getArchLblId());
                        }
                        for (ArchLabelDto archLabelDto : list) {
                            if(archLabelDto.getArchLblDtlId()!=0){
                                record.setHaveDetail("1");
                                break;
                            }
                        }

                    }
                }
            }
            return Response.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据类型查询所有档案失败：{}", e.getMessage());
            return Response.error("根据类型查询所有档案失败");
        }
    }

    @Override
    public Response uploadFile(MultipartFile file, String archMainCode) {
        try {
            String originalFilename = file.getOriginalFilename();
            long size = file.getSize();
            String fileSize = size/100 + "KB";
            String fileName = archMainCode + originalFilename;
            String filePath = constant.getUploadPath()+"Archives"+constant.getSplitChar() + fileName;
            File dest = new File(filePath);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("上传文件失败：{}", e.getMessage());
                throw new Exception("上传文件失败");
            }

            DigitalArchFiles digitalArchFile = new DigitalArchFiles();
            digitalArchFile.setFileName(originalFilename);
            String fileUrl=constant.getIp()+"Archives"+constant.getSplitChar()+fileName;
            digitalArchFile.setArchMainCode(archMainCode);
            digitalArchFile.setFileURL(fileUrl);
            digitalArchFile.setDownloadCount(0);
            digitalArchFile.setFileSize(fileSize);
            digitalArchFilesMapper.addFileRec(digitalArchFile);
            return Response.success(digitalArchFile.getArchFilesId());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件失败：{}", e.getMessage());
            return Response.error("上传文件失败");
        }
    }

    @Override
    public Response getSectList(String archDeptCode, String archCateCode) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String year = sdf.format(new Date());
            String archMainCode = year + "-" + archDeptCode + "-" + archCateCode;
            List<DigitalArchMain> codeList = digitalArchMainMapper.qryMainCode(archMainCode);

            List<String> list = new ArrayList<>();
            if(codeList.size()==0){
                list.add("0001");
            }else {
                for (DigitalArchMain digitalArchMain : codeList) {
                    String sect = digitalArchMain.getArchMainCode().substring(11, 15);

                    if (list.isEmpty()) {
                        list.add(sect);
                    } else {
                        String flag = "0";
                        for (String s : list) {
                            if (s.equals(sect)) {
                                flag = "1";
                            }
                        }
                        if ("0".equals(flag)) {
                            list.add(sect);
                        }
                    }
                }
                Collections.sort(list);
                String newSect=String.format("%04d",Integer.parseInt(list.get(list.size()-1))+1);
                list.add(newSect);
            }
            return Response.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询宗号失败：{}", e.getMessage());
            return Response.error("查询宗号失败");
        }
    }

    @Override
    public Response getArchMainCode(String archDeptCode, String archCateCode, String sect,String year) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            if(StringUtils.isBlank(year)){
                year = sdf.format(new Date());
            }
            String archMainCode = year + "-" + archDeptCode + "-" + archCateCode + "-" + sect;
            DigitalArchMain archMain = digitalArchMainMapper.queryHaveRec(archMainCode);
            String resCode="";
            if (archMain == null) {
                resCode=archMainCode + "-001";
            } else {
                int num = Integer.parseInt(archMain.getArchMainCode().substring(archMain.getArchMainCode().length() - 3));
                String res = String.format("%03d", num + 1);
                resCode=archMainCode + "-" + res;
            }
            return Response.success(resCode);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取档案编号失败：{}", e.getMessage());
            return Response.error("获取档案编号失败");
        }
    }

    @Override
    public void downLoadFile(String fileUrl, HttpServletResponse response,String archFilesId) {
        try {
            DigitalArchFiles archFiles=digitalArchFilesMapper.queryFile(archFilesId);
            String fileName=archFiles.getFileName();
            String archMainCode=archFiles.getArchMainCode();
            String markPath=constant.getUploadPath()+"WaterMark/waterMark.png";
            URL url = new URL(fileUrl);
            String tarImgPath=constant.getUploadPath()+"WaterMark/temp/"+fileName;
            if(fileUrl.endsWith("jpg")||fileUrl.endsWith("png")||fileUrl.endsWith("jpeg")||fileUrl.endsWith("bmp")){
                Image srcImg = ImageIO.read(url.openStream());
                int srcImgWidth = srcImg.getWidth(null);
                int srcImgHeight = srcImg.getHeight(null);
                log.info(srcImgWidth+"_"+srcImgHeight);
                BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
                // 加水印
                //创建画笔
                Graphics2D g = bufImg.createGraphics();
                //绘制原始图片
                g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
                // 水印文件
                Image srcWaterMark = ImageIO.read(new File(markPath));
                //获取水印图片的宽度
                int widthWaterMark= srcWaterMark.getWidth(null);
                //获取水印图片的高度
                int heightWaterMark = srcWaterMark.getHeight(null);
                //设置 alpha 透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
                //绘制水印图片  坐标为中间位置
//                g.drawImage(srcWaterMark, (srcImgWidth - widthWaterMark) / 2,
//                        (srcImgHeight - heightWaterMark) / 2, widthWaterMark, heightWaterMark, null);
                g.drawImage(srcWaterMark, (srcImgWidth -srcImgWidth/6),
                        (srcImgHeight -srcImgHeight/10), widthWaterMark/4, heightWaterMark/4, null);
                // 水印文件结束
                g.dispose();
                // 输出图片
                FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
                ImageIO.write(bufImg, "png", outImgStream);
                log.info("添加水印完成");
                outImgStream.flush();
                outImgStream.close();
            }else if(fileUrl.endsWith("pdf")){
                PdfReader reader = new PdfReader(fileUrl);
                PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(tarImgPath));

                //加载图片
                com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(markPath);
                image.scalePercent(15f);
                PdfGState gs = new PdfGState();
                gs.setFillOpacity(0.5f);//图片水印透明度
                //gs.setStrokeOpacity(0.4f);//设置笔触字体不透明度
                PdfContentByte content = null;

                int total = reader.getNumberOfPages();//pdf文件页数
                for (int i=0; i<total; i++) {
                    float x = reader.getPageSize(i + 1).getWidth();//页宽度
                    float y = reader.getPageSize(i + 1).getHeight();//页高度
                    content = stamper.getOverContent(i + 1);
                    content.setGState(gs);
                    content.beginText();//开始写入

                    if (i == total - 1) {
                        //每页7行，一行3个
//                        for (int j = 0; j < 3; j++) {
//                            for (int k = 0; k < 7; k++) {
//                                //setAbsolutePosition 方法的参数（输出水印X轴位置，Y轴位置）
//                                image.setAbsolutePosition(x / 3 * j - 30, y / 7 * k - 20);
//                                content.addImage(image);
//                            }
//                        }
                        image.setAbsolutePosition(x  - x/3, 0+y/30);
                        content.addImage(image);
                        content.endText();//结束写入
                    }
                }
                //关闭流
                stamper.close();
                reader.close();
            }else if(fileUrl.endsWith("doc")||fileUrl.endsWith("docx")) {
                // 创建Document对象并加载Word文档
                //创建一个 Document 实例
                Document document = new Document();
                document.loadFromFile(constant.getUploadPath()+"Archives/"+archMainCode+fileName);
                //加载图片
                DocPicture picture = new DocPicture(document);
                picture.loadImage(markPath);
                picture.setWidthScale(20);
                picture.setHeightScale(20);
                //设置文本环绕样式
                //picture.setTextWrappingStyle(TextWrappingStyle.Behind);
                for (int n = 0; n < document.getSections().getCount(); n++) {
                    if (n == document.getSections().getCount() - 1) {
                        Section section = document.getSections().get(n);
                        //获取该节的页眉
                        HeaderFooter footer = section.getHeadersFooters().getFooter();
                        Paragraph paragraph;
                        if (footer.getParagraphs().getCount() > 0) {
                            paragraph = footer.getParagraphs().get(0);
                        } else {
                            //添加段落到页眉中
                            paragraph = footer.addParagraph();
                        }

                        for (int p = 0; p < 1; p++) {
                            for (int q = 0; q < 1; q++) {
                                //复制图片并添加到多个位置
                                picture = (DocPicture)picture.deepClone();
                                picture.setVerticalPosition(1200);
                                picture.setHorizontalPosition(1200);
                                paragraph.getChildObjects().add(picture);
                            }
                        }
                    }
                }
                document.saveToFile(tarImgPath, FileFormat.Auto);
                document.dispose();
                log.info(tarImgPath);
            }
            String path=constant.getIp()+"WaterMark/temp/"+fileName;
            log.info("path:"+path);
            URL url2 = new URL(path);
            URLConnection conn = url2.openConnection();
            InputStream inputStream=conn.getInputStream();
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            //以Post方式提交表单，默认get方式
            ServletOutputStream out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            log.info("下载成功！");
            //更新文件下载次数
            digitalArchFilesMapper.updateDownloadTime(archFilesId);
            out.flush();
            out.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载文件失败！");
        }
    }

    @Override
    public Response updateArchMainState(int archMainId, int archState,String auditUser) {
        try {
            digitalArchMainMapper.updateArchMainState(archMainId, archState,auditUser);
            DigitalArchMain archMain=digitalArchMainMapper.qryArchMainById(archMainId);
            if(archState==5){
                ArchLabelMain archLabelMain=new ArchLabelMain();
                archLabelMain.setKnowId(archMainId);
                archLabelMain.setLblContent(archMain.getArchTitle());
                archLabelMain.setUserName(auditUser);
                archLabelMain.setNotes(archMain.getNotes());
                archLabelMainMapper.addArchLabelMain(archLabelMain);
            }
            //消息记录
            Message message=new Message();
            message.setType(2);
            message.setMessState(0);
            message.setOperator(archMain.getStaffCode());
            if(archState==5){
                message.setMessContent("您提交的档案名称为："+ archMain.getArchTitle()+"的档案归档已审批通过，审批人："+auditUser);
            }else if(archState==3){
                message.setMessContent("您提交的档案名称为："+ archMain.getArchTitle()+"的档案归档已被驳回，审批人："+auditUser);
            }
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改档案状态失败：{}", e.getMessage());
            return Response.error("修改档案状态失败");
        }
    }

    @Override
    public Response queryFilesById(String archMainCode,String recid) {
        try {
            int state=digitalArchMainMapper.getStateByMainCode(archMainCode);
            List<DigitalArchFiles> fileList=digitalArchFilesMapper.queryFilesById(archMainCode);
            String flag="0";
            if(StringUtils.isNotBlank(recid)){
                ArchApplication archApplication=archApplicationMapper.getApplyById(Integer.parseInt(recid));
                if(archApplication.getAppState()==5) {
                    Date now = new Date();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(archApplication.getEstBorrowDay());
                    calendar.add(Calendar.DAY_OF_MONTH, archApplication.getDuring());
                    if (now.getTime() > calendar.getTime().getTime()) {
                        flag = "1";
                        archApplicationMapper.updateState(Integer.parseInt(recid), 7);
                    }
                }
            }
            if(state==0||state==1||state==3||"1".equals(flag)){
                for (DigitalArchFiles digitalArchFiles : fileList) {
                    digitalArchFiles.setFileURL("");
                }
            }
            return Response.success(fileList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询档案相关的附件失败：{}", e.getMessage());
            return Response.error("查询档案相关的附件失败");
        }
    }

    @Override
    public Response getArchMainByCate() {
        try {

            List<ArchMainCountVo> list=digitalArchMainMapper.getCateCount();
            List<ArchMainCountVo> categoryList=archCategoryMapper.getCategory();
            for (ArchMainCountVo archMainCountVo : categoryList) {
                archMainCountVo.setCount(0);
                for (ArchMainCountVo mainCountVo : list) {
                    if(mainCountVo.getArchCateCode().equals(archMainCountVo.getArchCateCode())){
                        archMainCountVo.setCount(mainCountVo.getCount());
                    }
                }
            }
            return Response.success(categoryList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询首页档案类型和数量失败：{}", e.getMessage());
            return Response.error("查询首页档案类型和数量失败");
        }

    }

    @Override
    public Response getArchMainByMonth(String archCateCode,String startDate,String endDate) {
        try {
            if(StringUtils.isBlank(startDate)||StringUtils.isBlank(endDate)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
                String time = sdf.format(new Date());
                String year=time.substring(0,4);
                String month=time.substring(4,6);
                int m=Integer.parseInt(month);
                List<ArchMainMonthVo> list=new ArrayList<>();
                if(m!=12){
                    for (int i=m+1;i<=12;i++){
                        ArchMainMonthVo archMainMonthVo=new ArchMainMonthVo();
                        archMainMonthVo.setTime((Integer.parseInt(year)-1)+"-"+String.format("%02d", i));
                        archMainMonthVo.setCount(0);
                        list.add(archMainMonthVo);
                    }
                }
                for (int i=1;i<=m;i++){
                    ArchMainMonthVo archMainMonthVo=new ArchMainMonthVo();
                    archMainMonthVo.setTime(year+"-"+String.format("%02d", i));
                    archMainMonthVo.setCount(0);
                    list.add(archMainMonthVo);
                }
                if(m==12){
                    startDate=year+"01";
                    endDate=year+"12";
                }else{
                    startDate=String.valueOf(Integer.parseInt(year)-1)+(Integer.parseInt(month+1));
                    endDate=year+month;
                }
                List<ArchMainMonthVo> res = digitalArchMainMapper.getCountByMonth(archCateCode, startDate, endDate);

                for (ArchMainMonthVo re : res) {
                    for (ArchMainMonthVo archMainMonthVo : list) {
                        if(re.getTime().equals(archMainMonthVo.getTime())){
                            archMainMonthVo.setCount(re.getCount());
                        }
                    }
                }
                return Response.success(list);
            }else {
                String startYear = startDate.substring(0, 4);
                String startMonth = startDate.substring(4, 6);
                String endYear = endDate.substring(0, 4);
                String endMonth = endDate.substring(4, 6);
                List<ArchMainMonthVo> list = new ArrayList<>();
                if(startYear.equals(endYear)){
                    for (int j = Integer.parseInt(startMonth); j <= Integer.parseInt(endMonth); j++) {
                        ArchMainMonthVo archMainMonthVo = new ArchMainMonthVo();
                        archMainMonthVo.setTime(startYear + "-" + String.format("%02d", j));
                        archMainMonthVo.setCount(0);
                        list.add(archMainMonthVo);
                    }
                }else {
                    for (int i = Integer.parseInt(startYear); i <= Integer.parseInt(endYear); i++) {
                        if (i == Integer.parseInt(endYear)) {
                            for (int j = 1; j <= Integer.parseInt(endMonth); j++) {
                                ArchMainMonthVo archMainMonthVo = new ArchMainMonthVo();
                                archMainMonthVo.setTime(i + "-" + String.format("%02d", j));
                                archMainMonthVo.setCount(0);
                                list.add(archMainMonthVo);
                            }
                        } else if (i == Integer.parseInt(startYear)) {
                            for (int j = Integer.parseInt(startMonth); j <= 12; j++) {
                                ArchMainMonthVo archMainMonthVo = new ArchMainMonthVo();
                                archMainMonthVo.setTime(i + "-" + String.format("%02d", j));
                                archMainMonthVo.setCount(0);
                                list.add(archMainMonthVo);
                            }
                        } else {
                            for (int j = 1; j <= 12; j++) {
                                ArchMainMonthVo archMainMonthVo = new ArchMainMonthVo();
                                archMainMonthVo.setTime(i + "-" + String.format("%02d", j));
                                archMainMonthVo.setCount(0);
                                list.add(archMainMonthVo);
                            }
                        }
                    }
                }
                List<ArchMainMonthVo> res = digitalArchMainMapper.getCountByMonth(archCateCode, startDate, endDate);

                for (ArchMainMonthVo re : res) {
                    for (ArchMainMonthVo archMainMonthVo : list) {
                        if (re.getTime().equals(archMainMonthVo.getTime())) {
                            archMainMonthVo.setCount(re.getCount());
                        }
                    }
                }
                return Response.success(list);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据时间查询档案数量失败：{}", e.getMessage());
            return Response.error("根据时间查询档案数量失败");
        }
    }

    @Override
    public Response updateArchMainInfo(int archMainId, String archMainTitle, int archPeriod, String notes) {
        try {
            DigitalArchMain digitalArchMain = digitalArchMainMapper.qryArchMainById(archMainId);
            if(digitalArchMain.getArchState()>=5){
                return Response.bad("该状态下档案不允许修改");
            }
            digitalArchMainMapper.updateArchMainInfo(archMainId, archMainTitle, archPeriod, notes);
            return Response.success("");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改档案信息失败：{}", e.getMessage());
            return Response.error("修改档案信息失败");
        }
    }

    @Override
    public String addImportArchMain(DigitalArchMain digitalArchMain,String year,String sect) {
        digitalArchMain.setBorrowCount(0);
        digitalArchMain.setVisitCount(0);
        //默认公开
        digitalArchMain.setAccessState(0);
        digitalArchMain.setArchDeptHotName("");
        digitalArchMain.setArchRequireOther("");
        digitalArchMain.setDelivUnit(digitalArchMain.getArchDeptCode());
        String archMainCode = year + "-" + digitalArchMain.getArchDeptCode() + "-" + digitalArchMain.getArchCateCode() + "-" + sect;
        DigitalArchMain archMain = digitalArchMainMapper.queryHaveRec(archMainCode);
        String resCode="";
        if (archMain == null) {
            resCode=archMainCode + "-001";
        } else {
            int num = Integer.parseInt(archMain.getArchMainCode().substring(archMain.getArchMainCode().length() - 3));
            String res = String.format("%03d", num + 1);
            resCode=archMainCode + "-" + res;
        }
        digitalArchMain.setArchMainCode(resCode);
        digitalArchMainMapper.addImportArchMain(digitalArchMain);
        return resCode;
    }

    @Override
    public Response getArchMain(String archMainTitle, String username, int archState,int pageNum,int pageSize) {
        try {
            Page<DigitalArchMain> page = new Page<>(pageNum, pageSize);

            if(archState==-1){
                digitalArchMainMapper.getAllArchMain(page,archMainTitle,username);
            }else if(archState==1){
                digitalArchMainMapper.getArchMainOne(page,archMainTitle,username);
            }else{
                digitalArchMainMapper.getArchMainByState(page,archState,archMainTitle);
            }

            return Response.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询档案失败：{}", e.getMessage());
            return Response.error("查询档案失败");
        }
    }

    @Override
    public Response getTypeAndNum() {
        try {
            List<ArchTypeAndNumVo> list=new ArrayList<>();
            ArchTypeAndNumVo hotPoint=new ArchTypeAndNumVo();
            List<ArchTypeAndNumDto> hotPointList=digitalArchMainMapper.getHotPointList();
            hotPoint.setArchType("热点标签");
            hotPoint.setArchTypeAndNumDtoList(hotPointList);
            ArchTypeAndNumVo year=new ArchTypeAndNumVo();
            List<ArchTypeAndNumDto> yearList=digitalArchMainMapper.getYearList();
            year.setArchType("年度");
            year.setArchTypeAndNumDtoList(yearList);
            ArchTypeAndNumVo archType=new ArchTypeAndNumVo();
            List<ArchTypeAndNumDto> archTypeList=digitalArchMainMapper.getArchTypeList();
            archType.setArchType("档案类别");
            archType.setArchTypeAndNumDtoList(archTypeList);
            list.add(hotPoint);
            list.add(year);
            list.add(archType);
            return Response.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询档案类型和数量失败：{}", e.getMessage());
            return Response.error("查询档案类型和数量失败");
        }
    }

    @Override
    public Response getArchMainByType(String type, String typeName,int pageSize,int pageNum) {
        try {
            Page<DigitalArchMain> page = new Page<>(pageNum, pageSize);
            if("1".equals(type)){
                digitalArchMainMapper.getArchMainByHot(page,typeName);
            }else if("2".equals(type)){
                digitalArchMainMapper.getArchMainByYear(page,typeName);
            }else if("3".equals(type)){
                digitalArchMainMapper.getArchMainByCate(page,typeName);
            }
            return Response.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询该类型的档案失败：{}", e.getMessage());
            return Response.error("查询该类型的档案失败");
        }
    }

    @Override
    public Response getArchMainByMuchType(String hotPoint, String year, String cateType, int pageSize, int pageNum) {
        try {
            Page<DigitalArchMain> page = new Page<>(pageNum, pageSize);

            digitalArchMainMapper.getArchMainByMuchType(page,hotPoint,year,cateType);

            return Response.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询该类型的档案失败：{}", e.getMessage());
            return Response.error("查询该类型的档案失败");
        }
    }

    @Override
    public Response qryMyDeptArchMain(String deptCode) {
        try {
            List<ArchMainTypeVo> list=digitalArchMainMapper.getMyHotPoint(deptCode);
            List<ArchMainDto> archMainDtoList=digitalArchMainMapper.getArchMainByCode(deptCode);
            Map<String,List<String>> hashMap= new HashMap<>();

            for (ArchMainDto archMainDto : archMainDtoList) {
                if(!hashMap.containsKey(archMainDto.getArchDeptHotName()+archMainDto.getArchCateName())){
                    List<String> yearList=new ArrayList<>();
                    yearList.add(archMainDto.getYearTime());
                    hashMap.put(archMainDto.getArchDeptHotName()+archMainDto.getArchCateName(),yearList);
                }else{
                    hashMap.get(archMainDto.getArchDeptHotName()+archMainDto.getArchCateName()).add(archMainDto.getYearTime());
                }
            }

            for (ArchMainTypeVo archMainTypeVo : list) {

                List<CateAndYearDto> cateAndYearDtoList=digitalArchMainMapper.getCateByHotPoint(archMainTypeVo.getArchDeptHotName(),deptCode);
                for (CateAndYearDto cateAndYearDto : cateAndYearDtoList) {
                    List<String> newList = new ArrayList<String>(new LinkedHashSet<String>(hashMap.get(archMainTypeVo.getArchDeptHotName()+cateAndYearDto.getArchCateName())));
                    cateAndYearDto.setYearList(newList);
                }
                archMainTypeVo.setCateAndYearDtoList(cateAndYearDtoList);
                if("".equals(archMainTypeVo.getArchDeptHotName())){
                    archMainTypeVo.setArchDeptHotName("其他");
                }
            }

            return Response.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询该类型的档案失败：{}", e.getMessage());
            return Response.error("查询该类型的档案失败");
        }
    }

    @Override
    public Response qryMyDeptArchMainByType(String deptCode, String year, String hotPoint, String cateName, int pageNum, int pageSize,String archTitle) {
        try {
            Page<DigitalArchMain> page = new Page<>(pageNum, pageSize);
            if("其他".equals(hotPoint)){
                hotPoint="";
            }
            String cateCode=archCategoryMapper.getCateCodeByName(cateName);
            digitalArchMainMapper.qryMyDeptArchMainByType(page,hotPoint,year,cateCode,deptCode,archTitle);

            return Response.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询该类型的档案失败：{}", e.getMessage());
            return Response.error("查询该类型的档案失败");
        }
    }

}
